package com.pxd.HandlerInterceptor;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@Component
//public class MyRequestListener implements ServletRequestListener{
//    @Override
//    public void requestInitialized(ServletRequestEvent sre) {
//        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
//        String ip = request.getRemoteAddr();
//        String url = request.getRequestURL().toString();
//        String id = request.getSession().getId();
//        System.out.println(ip);
//        System.out.println(url);
//        System.out.println(id);
//        ServletRequestListener.super.requestInitialized(sre);
//    }
//
//    @Override
//    public void requestDestroyed(ServletRequestEvent sre) {
//        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
//        String sessionID = request.getSession().getId();
//        System.out.println(sessionID+"的请求已经销毁");
//        ServletRequestListener.super.requestDestroyed(sre);
//    }
//}

@RestController
class a{
    @RequestMapping("a")
    public String a(HttpServletRequest request){
        request.getSession();
        ServletContext servletContext = request.getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        System.out.println(count);
        return  "在线人数"+count;

    }
}

@Component
class CountListener implements HttpSessionListener{
    private Integer count=0;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        count++;
        se.getSession().getServletContext().setAttribute("count",count);
//        HttpSessionListener.super.sessionCreated(se);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        count--;
        se.getSession().getServletContext().setAttribute("count",count);
//        HttpSessionListener.super.sessionDestroyed(se);
    }
}